#include "carina/common/global.hh"
#include "carina/common/testing.hh"
#include "carina/file-system.hh"

#include <cstdio>

// What we test in this test case scenario is whether
// the polling service detects changes when new directories
// get created or files get modified within the monitored directory.

CE_TEST("Testing file system library capabilities.")
{   
	// Lets create our own directory to prevent spurious triggering of some asserts.
#define TEST_DIR Carina_TESTS_DIR "/test"
	auto ret = Carina::Directory::mkdir(TEST_DIR);
	CE_ASSERT(ret != Carina::CE_FS_ERROR, "Failed to create test directory.");

    Carina::Directory::rmdir(TEST_DIR "/testdir");
    
    Carina::FSPollingService poller;
    
    poller.addWatch(Carina::Path(TEST_DIR));
    
    ret = Carina::Directory::mkdir(TEST_DIR "/testdir");
    CE_ASSERT(ret != Carina::CE_FS_EXISTS, "Directory was just deleted. It should not exist.");
    
    Carina::FSEvents evts;
    
    poller.poll(evts);
    
    CE_ASSERT(evts.size() == 1, "Single event expected for directory creation.");
    CE_ASSERT(evts[0].type & Carina::CE_FS_EVENT_CREATE, "Unmatching events.");
    CE_ASSERT(evts[0].name == "testdir", "Unmatching directory name."
              "Are you sure that you have not created another directory at the same time?");

    const char* filename = TEST_DIR "/test.txt";
    std::fstream fs(TEST_DIR "/test.txt", std::ios::out);
    CE_ASSERT(fs.is_open(), "Could not open file writing");
    fs << "Hello world!" << std::endl;
    fs.close();
    
    auto err = remove(filename);
    CE_ASSERT(!err, "Failed to remove file.");
    
    poller.poll(evts);
    
    CE_ASSERT(evts.size() == 3, "Unexpected number of events.");
    
    poller.poll(evts);
    
    CE_ASSERT(evts.empty(), "File system event encountered without anything being done by the application");

	poller.removeWatch(Carina::Path(TEST_DIR));
}